package com.j3a.journal.generic;

import java.io.Serializable;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class DaoGeneric<T, PK extends Serializable> implements IDaoGeneric<T, PK> {

    // Injection par Spring
    @Autowired
    protected SessionFactory sessionFactory;
    protected Class<T>       type;

    // Le constructeur
    public DaoGeneric( Class<T> type ) {
        this.type = type;
    }

    @Override
    public T ajouter( T t ) {
        sessionFactory.getCurrentSession().save( t );
        return t;
    }

    @Override
    public T modifier( T t ) {
        sessionFactory.getCurrentSession().merge( t );
        return t;
    }

    @Override
    public void supprimer( T t ) {
        sessionFactory.getCurrentSession().delete( t );
    }

    @SuppressWarnings( "unchecked" )
    @Override
    public List<T> lister() {
        String query = "from" + " " + type.getSimpleName();
        List<T> liste = sessionFactory.getCurrentSession().createQuery( query ).list();
        return liste;
    }

    @SuppressWarnings( "unchecked" )
    @Override
    public T selectionner( PK k ) {
        return (T) sessionFactory.getCurrentSession().get( type, k );
    }

    // Les accesseurs
    public Class<T> getType() {
        return type;
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory( SessionFactory sessionFactory ) {
        this.sessionFactory = sessionFactory;
    }

}
